import re
import requests


def mergeDict(dic1, dic2):
    """合并字典，同时间戳则建立列表"""
    for key in dic1:
        if dic2.get(key):
            dic2[key] = [dic2[key]]
            dic2[key].append(dic1[key])
        else:
            dic2[key] = [dic1[key]]
    return dic2


def getMusicInfo(item_name):
    """搜索歌曲，获得id"""
    url = 'https://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s={' + item_name + \
          '}&type=1&offset=0&total=true&limit=2'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/89.0.4389.114 Safari/537.36 '
    }
    try:
        id_get = requests.get(url, headers=headers)
    except requests.exceptions.ConnectionError:
        print('网络连接失败')
        return {"id": 0, "name": '无', "artist": '无'}
    music_id = id_get.json()["result"]['songs'][0]['id']
    music_name = id_get.json()["result"]['songs'][0]['name']
    music_artists = id_get.json()["result"]['songs'][0]['artists']
    music_artist = ''
    for artist in music_artists:
        if music_artist != '':
            music_artist += '/' + artist['name']
        else:
            music_artist += artist['name']
    return {"id": music_id, "name": music_name, "artist": music_artist}


def getLyric(music_id):
    """根据歌曲id获取歌词"""
    print(music_id)
    if music_id == 0:
        return ''
    lrc_url = 'https://music.163.com/api/song/lyric?id=' + str(music_id) + '&lv=1&kv=1&tv=-1'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/89.0.4389.114 Safari/537.36 '
    }
    try:
        lyric_get = requests.get(lrc_url, headers=headers)
    except requests.exceptions.ConnectionError:
        print('网络连接失败')
        return ''

    try:
        # 获取歌词
        lyric_raw = lyric_get.json()['lrc']['lyric']
        lyric_zh = lyric_get.json()['tlyric']['lyric']
    except KeyError:
        print(lyric_get.text)
        return ''

    print('获取成功！')
    if lyric_zh == '':
        # 无翻译，返回原始歌词
        return lyric_raw

    # 以换行符分割
    lrc_list_zh = lyric_zh.splitlines()
    lrc_list_raw = lyric_raw.splitlines()

    # 提取翻译作者，限网易云
    by = ''
    if lrc_list_zh[0].find('by:') != -1:
        by = lrc_list_zh.pop(0)
        by = by + '\n'

    # 时间戳正则
    func = re.compile("\[.*?]")
    # 根据时间戳，转换成字典
    lrc_dict_zh = {}
    for i in lrc_list_zh:
        if func.search(i) is None:
            continue
        lrc_time = func.search(i).group()
        lrc_text = func.sub('', i)
        lrc_text = ' '.join(lrc_text.split())
        lrc_dict_zh[lrc_time] = lrc_text

    lrc_dict_raw = {}
    for i in lrc_list_raw:
        if func.search(i) is None:
            continue
        lrc_time = func.search(i).group()
        lrc_text = func.sub('', i)
        lrc_text = ' '.join(lrc_text.split())
        lrc_dict_raw[lrc_time] = lrc_text

    lrc_dic_merge = mergeDict(lrc_dict_zh, lrc_dict_raw)
    # 时间戳排序
    list_up = sorted(lrc_dic_merge)
    lrc_output = by
    # 根据时间戳顺序重构歌词
    for i in list_up:
        if type(lrc_dic_merge[i]) is str:
            lrc_output = lrc_output + i + lrc_dic_merge[i] + '\n'
        elif lrc_dic_merge[i][0] == '':
            lrc_output = lrc_output + i + lrc_dic_merge[i][0] + '\n'
        else:
            lrc_output = lrc_output + i + lrc_dic_merge[i][0] + '\n' + i + lrc_dic_merge[i][-1] + '\n'
    return lrc_output


def getMusicComment(music_id):
    """获取评论"""
    url = f'http://music.163.com/api/v1/resource/comments/R_SO_4_{music_id}?limit=20&offset=0'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/89.0.4389.114 Safari/537.36 '
    }
    try:
        info_get = requests.get(url, headers=headers)
    except requests.exceptions.ConnectionError:
        print('网络连接失败')
        return {"LrcMusicPlayer": "网络连接失败"}
    print('获取成功！')
    hot_comments_list = info_get.json()["hotComments"]
    user_dict = {}
    if hot_comments_list:
        for item in hot_comments_list:
            name = item["user"]["nickname"]
            user_dict[name] = item["content"]
    else:
        comments_list = info_get.json()["comments"]
        for item in comments_list:
            name = item["user"]["nickname"]
            user_dict[name] = item["content"]
    return user_dict
